package DEMO;

import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * @author Lzm
 * @version 1.0
 */
public class ThreadPoolTest {
  // 创建线程池, 线程池中有5个线程
  private ExecutorService executorService = Executors.newFixedThreadPool(5);

  // 创建周期线程池, 每个一段时间执行一次代码
  private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);

  private void sleep(long m){
    try {
      Thread.sleep(m);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  @Test
  // 1. 测试普通线程池
  public void ExecutorServiceTest(){
    // 指定线程执行任务
    Runnable task = new Runnable() {
      @Override
      public void run() {
        System.out.println(Thread.currentThread().getName() + "Hello,world");
      }
    };
    for (int i = 0; i < 10; i++) {
      executorService.submit(task);
    }

    sleep(10000);
  }

  @Test
  // 2. 测试定时线程池
  public void ScheduledExecutorServiceTest(){
    // 指定线程执行任务
    Runnable task = new Runnable() {
      @Override
      public void run() {
        System.out.println(Thread.currentThread().getName() + "Hello,world");
      }
    };
      scheduledExecutorService.scheduleAtFixedRate(task,100,1000, TimeUnit.MILLISECONDS);

      sleep(20000);
  }


  public static void main(String[] args) {
    // 1. 创建Semaphore对象
    Semaphore semaphore = new Semaphore(3);
    for (int i = 0; i < 10; i++) {
      // 2. 规定一次最多只能3个线程可以访问资源
      new Thread(new Runnable() {
        @Override
        public void run() {
          try {
            semaphore.acquire();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          try {
            System.out.println("running");
          } finally {
            // 3. 释放
            semaphore.release();
          }
        }
      }).start();
    }
  }
}
